from django.db import transaction
from django.db.models import F
from rest_framework import serializers

from production_info.models import InspectionRecordModel, ProductTaskModel


class InspectionRecordSerializer(serializers.ModelSerializer):
    """
    验收记录的序列化器
    """

    class Meta:
        model = InspectionRecordModel
        fields = '__all__'

    def create(self, validated_data):
        """
        1、插入一条验收记录数据
        2、修改生产任务中的： 验收合格数量
        :param validated_data:
        :return:
        """
        with transaction.atomic():
            # 第一件事情搞定
            irm: InspectionRecordModel = super(InspectionRecordSerializer, self).create(validated_data)
            # 修改生产任务中的： 验收合格数量
            ProductTaskModel.objects.filter(id=irm.product_task_id) \
                .update(check_number=F('check_number') + irm.qualified_count)
            return irm
